<?php

namespace App\Cache;

use App\Helpers\RedisUtil;
use App\Model\UserRemark;
use Hyperf\Redis\Redis;
use Hyperf\Di\Annotation\Inject;
class UserRemarkCache
{
    use \Hyperf\Di\Aop\ProxyTrait;
    use \Hyperf\Di\Aop\PropertyHandlerTrait;
    function __construct()
    {
        $this->__handlePropertyHandler(__CLASS__);
    }
    /**
     * @Inject
     * @var Redis
     */
    protected $redis;
    /**
     * 设置备注
     * @param $userId
     * @param $toUserId
     * @return bool
     * @throws \RedisException
     */
    public function getRemark($userId, $toUserId)
    {
        $key = RedisKey::userRemarkList($userId);
        if (RedisUtil::getRedis()->exists($key)) {
            $data = RedisUtil::getRedis()->get($key);
            if (empty($data)) {
                return '';
            }
            $data = json_decode($data, true);
            return $data[$toUserId] ?? '';
        } else {
            $data = UserRemark::where('user_id', $userId)->pluck('remark', 'to_user_id')->toArray();
            if (empty($data)) {
                return '';
            }
            $this->redis->setex($key, 86400, json_encode($data));
            return $data[$toUserId] ?? '';
        }
    }
}